package com.atguigu.daijia.driver.service.impl;

import com.alibaba.nacos.common.codec.Base64;
import com.atguigu.daijia.common.result.Result;
import com.atguigu.daijia.driver.config.TencentCloudProperties;
import com.atguigu.daijia.driver.service.CosService;
import com.atguigu.daijia.driver.service.OcrService;
import com.atguigu.daijia.model.vo.driver.CosUploadVo;
import com.atguigu.daijia.model.vo.driver.DriverLicenseOcrVo;
import com.atguigu.daijia.model.vo.driver.IdCardOcrVo;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.DriverLicenseOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.DriverLicenseOCRResponse;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.boot.autoconfigure.integration.IntegrationProperties;
import org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapProperties;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.DateFormat;
import java.time.format.DateTimeFormatter;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class OcrServiceImpl implements OcrService {

    @Resource
    private CosService cosService;
    @Resource
    private TencentCloudProperties tencentCloudProperties;
    @Override
    public IdCardOcrVo idCardOcr(MultipartFile file) {

        try {
            //图片转换称base64格式字符串
            byte[] base64 = Base64.encodeBase64(file.getBytes());
            String fileBase64 = new String(base64);//将字节转成字符串
            System.out.println(fileBase64);
            //实例化一认证对象，入参需要传入腾讯云账户 SecrectId 和 Secrectkey ，此处还需要注意密钥对的保密
            Credential cred = new Credential(tencentCloudProperties.getSecretId(), tencentCloudProperties.getSecretKey());
            //实例化一个http选项，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            //实例化一个client选项，，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            //实例化要请求产品的client对象,clientProfile是可选的
            OcrClient client = new OcrClient(cred, tencentCloudProperties.getRegion());
            //实例化一个请求对象，每个接口都会对应一个request对象
            IDCardOCRRequest req = new IDCardOCRRequest();
            //设置文件
            req.setImageBase64(fileBase64);
            //返回的resp是一个IDCardOCRResponse的示例，与请求对象对应
            IDCardOCRResponse resp = client.IDCardOCR(req);
            //转换为IDCardOcrVo对象(其实resp中的内容就是省份证的内容)
            IdCardOcrVo idCardOcrVo = new IdCardOcrVo();
            if(StringUtils.hasText(resp.getName())){//能拿到名字肯定是正面
                //省份证正面
                idCardOcrVo.setName(resp.getName());//姓名
                idCardOcrVo.setGender("男".equals(resp.getSex())?"1":"2");//性别
                idCardOcrVo.setBirthday(DateTimeFormat.forPattern("yyyy/MM/dd").parseDateTime(resp.getBirth()).toDate());//出生年月
                idCardOcrVo.setIdcardNo(resp.getIdNum());
                idCardOcrVo.setIdcardAddress(resp.getAddress());

                //上传身份证正面图片到腾讯云cos
                CosUploadVo cosUploadVo = cosService.upload(file,"idCard");
                idCardOcrVo.setIdcardFrontUrl(cosUploadVo.getUrl());
                idCardOcrVo.setIdcardFrontShowUrl(cosUploadVo.getShowUrl());
            }
            else{
                //身份证反面
                //证件有效期："2010.07.21-2020.07.21"
                String idcardExpireString = resp.getValidDate().split("-")[1];
                idCardOcrVo.setIdcardExpire(DateTimeFormat.forPattern("yyyy.MM.dd").parseDateTime(idcardExpireString).toDate());

                //上传省份证背面到腾讯云cos
                CosUploadVo cosUploadVo = cosService.upload(file, "idCrad");
                idCardOcrVo.setIdcardBackUrl(cosUploadVo.getUrl());
                idCardOcrVo.setIdcardBackShowUrl(cosUploadVo.getShowUrl());

            }
            return idCardOcrVo;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public DriverLicenseOcrVo driverLicenseOcr(MultipartFile file) {
        //将图片转换成字符串
        try {
            byte[] base64 = Base64.encodeBase64(file.getBytes());
            String filebase64 = new String(base64);
            //实例化一认证对象，入参需要传入腾讯云账户 SecrectId 和 Secrectkey ，此处还需要注意密钥对的保密
            Credential credential = new Credential(tencentCloudProperties.getSecretId(), tencentCloudProperties.getSecretKey());
            //实例化要请求产品的Ocrclient对象,clientProfile是可选的
            OcrClient client = new OcrClient(credential, tencentCloudProperties.getRegion());
            //实例化一个请求对象(request)，每个接口都会对应一个request对象
            DriverLicenseOCRRequest request = new DriverLicenseOCRRequest();
            //设置读取文件
            request.setImageBase64(filebase64);
            //返回的resp是一个DriverLicenseResponse的示例，与请求对象对应
            DriverLicenseOCRResponse response = client.DriverLicenseOCR(request);//resp里面就是包含驾驶证（省份证)内容的对象,但是读取的驾驶证的内容全是字符串形式的
            //所以下面的日期需要将字符串转换成日期类型
            //把转换成DriverLicenseOcrVo对像
            DriverLicenseOcrVo driverLicenseOcrVo = new DriverLicenseOcrVo();
            //驾驶证正面
            if(StringUtils.hasText(response.getName())){
                driverLicenseOcrVo.setName(response.getName());
                driverLicenseOcrVo.setName(response.getName());
                driverLicenseOcrVo.setDriverLicenseClazz(response.getClass_());
                driverLicenseOcrVo.setDriverLicenseNo(response.getCardCode());
                //驾驶证件发行日期
                driverLicenseOcrVo.setDriverLicenseIssueDate(DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime(response.getDateOfFirstIssue()).toDate());
                driverLicenseOcrVo.setDriverLicenseExpire(DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime(response.getEndDate()).toDate());
                //上传驾驶证正面图片到腾讯云cos
                CosUploadVo cosUploadVo = cosService.upload(file, "driverLicense");
                //把显示地址和回显地址拿到
                driverLicenseOcrVo.setDriverLicenseFrontShowUrl(cosUploadVo.getShowUrl());
                driverLicenseOcrVo.setDriverLicenseBackUrl(cosUploadVo.getUrl());
            }
            //驾驶证背面
            else{
                //驾驶证反面
                //上传驾驶证反面图片到腾讯云cos
                CosUploadVo cosUploadVo =  cosService.upload(file, "driverLicense");
                driverLicenseOcrVo.setDriverLicenseBackUrl(cosUploadVo.getUrl());
                driverLicenseOcrVo.setDriverLicenseBackShowUrl(cosUploadVo.getShowUrl());
            }
            return driverLicenseOcrVo;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
